import { Button, Col, Input, Row, Space, Table } from "antd";
import { FC, Key, ReactNode, useCallback, useState } from "react";
import { useRequest } from "ahooks";
import { request } from "@/utils/request.ts";

interface BaseTableProps {
  columns: any;
  api: string;
  toolbarRender?: () => ReactNode;
}

const BaseTable: FC<BaseTableProps> = ({ columns, api, toolbarRender }) => {
  // 当前勾选的数据
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  // 勾选
  const rowSelectionChange = useCallback(
    (selectedRowKeys: Key[], selectedRows: API.RoleObject[]) => {
      console.log("onChange", selectedRowKeys, selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    []
  );
  // 分页
  const paginationChange = useCallback((page: number, pageSize: number) => {
    // 使用 page, pageSize 修改我们自己的 state 数据
    setQuery((que) => ({ ...que, page: page, size: pageSize }));
  }, []);
  const [query, setQuery] = useState({
    page: 1,
    size: 10,
  });
  const { data, loading, refresh } = useRequest(
    () => request.post(api + "/page", query),
    {
      refreshDeps: [query],
    }
  );

  return (
    <Space direction="vertical" style={{ display: "flex" }}>
      <Row>
        {/* 操作按钮区域 */}
        <Col flex={1}>
          <Space>
            <Button type="default" onClick={refresh}>
              刷新
            </Button>
            <Button type="default" danger disabled={!selectedRowKeys.length}>
              删除
            </Button>
            {toolbarRender && toolbarRender()}
          </Space>
        </Col>
        {/*  搜索区域 */}
        <Col>
          <Input.Search placeholder="请输入关键字" />
        </Col>
      </Row>
      <Table
        rowKey="id"
        rowSelection={{
          onChange: rowSelectionChange,
        }}
        loading={loading}
        dataSource={data?.list}
        columns={columns}
        scroll={{ y: 300 }}
        pagination={{
          total: data?.pagination.total,
          showSizeChanger: true,
          onChange: paginationChange,
        }}
      />
    </Space>
  );
};

export default BaseTable;
